package com.xy.service.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xy.api.exception.BizException;
import com.xy.api.model.dto.system.NotificationsDTO;
import com.xy.api.service.system.INotificationsService;
import com.xy.auth.UserContext;
import com.xy.mapper.system.NotificationsMapper;
import com.xy.model.po.system.NotificationsPO;
import com.xy.utils.CustomBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class NotificationsServiceImpl implements INotificationsService {

    @Autowired
    private NotificationsMapper notificationsMapper;

    @Override
    public void maskRead(Long id) {
        NotificationsPO existNotice = notificationsMapper.selectById(id);
        if (null == existNotice) {
            throw new BizException("消息不存在");
        }
        Long receiverId = existNotice.getReceiverId();
        Long currentUserId = UserContext.get().getId();
        if (!Objects.equals(receiverId, currentUserId)) {
            throw new BizException("接受人异常");
        }
        existNotice.setIsRead(1);
        notificationsMapper.updateById(existNotice);
    }


    @Override
    public void clearUnRead() {
        Long currentUserId = UserContext.get().getId();
        LambdaQueryWrapper<NotificationsPO> query = new LambdaQueryWrapper<>();
        query
                .eq(NotificationsPO::getReceiverId, currentUserId)
                .eq(NotificationsPO::getIsRead, 0)
                .eq(NotificationsPO::getIsDeleted, 0);

        NotificationsPO record = new NotificationsPO();
        record.setIsRead(1);
        record.setUpdateBy(currentUserId);
        notificationsMapper.update(record, query);
    }

    @Override
    public List<NotificationsDTO> queryUnRead() {
        Long currentUserId = UserContext.get().getId();
        LambdaQueryWrapper<NotificationsPO> query = new LambdaQueryWrapper<>();
        query
                .eq(NotificationsPO::getReceiverId, currentUserId)
                .eq(NotificationsPO::getIsRead, 0)
                .eq(NotificationsPO::getIsDeleted, 0);
        List<NotificationsPO> notificationsPOS = notificationsMapper.selectList(query);
        List<NotificationsDTO> notifications = CustomBeanUtil.copyListProperties(notificationsPOS, NotificationsDTO::new);
        return notifications;
    }
}
